import 'dart:io';
import 'dart:typed_data';

import 'package:ble2301/ble_sdk.dart';
import 'package:ble2301/utils/resolve_util.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:path_provider/path_provider.dart';
import 'package:share_extend/share_extend.dart';
import 'package:toast/toast.dart';

import '../util/app_all_value.dart';
import '../util/event_bus.dart';

class CmdSendPage extends StatefulWidget {
  const CmdSendPage({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() => _cmdSendState();
}

class _cmdSendState extends State<CmdSendPage> {
  AppAllValueController controller = Get.find();
  int selectedValue = 1;
  var selectValue = "16";
  List<String> cmdList = List<String>.generate(16, (int index) {
    return "00";
  });
  List<String> tabList = ["保存记录", "导出记录", "发送", "清除"];
  List<String> historyList = [];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("指令"),
      ),
      body: ListView.builder(
          itemBuilder: (context, index) {
            if (index == 0) {
              return Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Radio(
                    value: 1,
                    groupValue: selectedValue,
                    onChanged: (value) {
                      setState(() {
                        selectedValue = value as int;
                      });
                    },
                  ),
                  Text("CRC"),
                  Radio(
                    value: 2,
                    groupValue: selectedValue,
                    onChanged: (value) {
                      setState(() {
                        selectedValue = value as int;
                      });
                    },
                  ),
                  Text("Not CRC")
                ],
              );
            } else if (index == 1) {
              return Container(
                child: Row(
                  children: [
                    Text("选择指令长度\nSelect instruction length"),
                    SizedBox(
                      width: 30,
                    ),
                    DropdownButton(
                      value: selectValue,
                      items: getMenuList()
                          .map((e) => DropdownMenuItem(
                                child: Text(e),
                                value: e,
                              ))
                          .toList(),
                      onChanged: (String? value) {
                        if (value != null) {
                          setState(() {
                            selectValue = value;
                            List<String> numList = List<String>.generate(
                                int.parse(selectValue), (int index) {
                              return "00";
                            });
                            cmdList.clear();
                            cmdList.addAll(numList);
                          });
                        }
                      },
                    )
                  ],
                ),
              );
            } else if (index == 2) {
              return Container(
                margin: EdgeInsets.symmetric(horizontal: 15),
                child: GridView.builder(
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 4, // Number of columns
                    mainAxisSpacing: 2.0, // Spacing between rows
                    crossAxisSpacing: 10.0, // Spacing between columns
                    childAspectRatio:
                        2, // Ratio of the width to the height of each grid item
                  ),
                  itemBuilder: (context, index) {
                    return TextField(
                      textAlign: TextAlign.center,
                      inputFormatters: [
                        FilteringTextInputFormatter.allow(
                            RegExp(r'[a-zA-Z0-9]')),
                      ],
                      maxLength: 2,
                      controller: TextEditingController(text: cmdList[index]),
                      decoration: InputDecoration(
                          contentPadding: EdgeInsets.symmetric(
                              vertical: 0.0, horizontal: 0),
                          counterText: ''),
                      onChanged: (text) {
                        cmdList[index] = text;
                      },
                    );
                  },
                  itemCount: cmdList.length,
                  shrinkWrap: true,
                ),
              );
            } else if (index == 3) {
              return Container(
                margin: EdgeInsets.only(left: 15, right: 15, top: 30),
                child: GridView.builder(
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 3, // Number of columns
                    mainAxisSpacing: 10.0, // Spacing between rows
                    crossAxisSpacing: 10.0, // Spacing between columns
                    childAspectRatio:
                        3.0, // Ratio of the width to the height of each grid item
                  ),
                  itemBuilder: (context, index) {
                    return SizedBox(
                        height: 50,
                        child: GestureDetector(
                          onTap: () {
                            switch (index) {
                              case 0:
                                //保存记录
                                saveFile();
                                break;
                              case 1:
                                //导出记录
                                exportFile();
                                break;
                              case 2:
                                //发送
                                sendText();
                                break;
                              case 3:
                                //清空
                                cleanList();
                                break;
                            }
                            if (index == 0) {}
                          },
                          child: Container(
                              alignment: Alignment.center,
                              decoration: BoxDecoration(
                                  color: Colors.grey,
                                  borderRadius: BorderRadius.circular(6)),
                              child: Text(tabList[index])),
                        ));
                  },
                  itemCount: tabList.length,
                  shrinkWrap: true,
                ),
              );
            } else if (index == 4) {
              return ListView.builder(
                  itemBuilder: (context, index) {
                    return Container(
                      child: Text(
                        historyList[index],
                        style: TextStyle(fontSize: 12),
                      ),
                      margin: EdgeInsets.only(top: 0, left: 0, right: 0),
                    );
                  },
                  shrinkWrap: true,
                  itemCount: historyList.length,
                  physics: NeverScrollableScrollPhysics());
            }
          },
          itemCount: 5,
          shrinkWrap: true),
    );
  }

  List<String> getMenuList() {
    List<String> list = [];
    for (int i = 16; i < 200; i++) {
      list.add(i.toString());
    }
    return list;
  }

  void sendText() {
    List<int> listHex = cmdList.map((e) => int.parse(e, radix: 16)).toList();
    Uint8List uintValue = BleSDK.sendHex(listHex, selectedValue == 1);
    controller.writeData(uintValue);
    setState(() {
      historyList.add("Send：" + ResolveUtil.intList3String(listHex));
    });
  }

  void cleanList() async {
    final path = await _localPath;
    final file = await File('$path/data.txt');
    if (file.existsSync()) {
      file.deleteSync();
    }
    file.delete();
    setState(() {
      historyList.clear();
    });
  }

  void exportFile() async {
    if (historyList.length > 0) {
      //保存文件
      String historyChar = historyList.join("\n").toString();
      String fileName =
          "data_" + DateTime.now().microsecond.toString() + ".txt";
      File file = await writeDataToLocalFile(historyChar, fileName);
      await shareFile(file);
    }
  }

  void saveFile() async {
    if (historyList.length > 0) {
      //保存文件
      String historyChar = historyList.join("\n").toString();
      String fileName =
          "data_" + DateTime.now().microsecond.toString() + ".txt";
      writeDataToLocalFile(historyChar, fileName);
      // Fluttertoast.showToast(msg: );

      Toast.show("保存文件成功");
    }
  }

  Future<String> get _localPath async {
    final directory = await getApplicationDocumentsDirectory();
    return directory.path;
  }

  Future<File> writeDataToLocalFile(String data, String fileName) async {
    final path = await _localPath;

    final file = File('$path/$fileName');
    return file.writeAsString(data);
  }

  Future<void> shareFile(File file) async {
    try {
      List<String> paths = [file.path];
      await ShareExtend.share(file.path, "file");
      // await Share.shareFiles(paths, text: 'Sharing file');
    } catch (e) {
      print('Error sharing file: $e');
    }
  }

  @override
  void dispose() {
    super.dispose();
    EventBus().off('dataByteCallBack');
  }

  @override
  void initState() {
    super.initState();
    EventBus().on('dataByteCallBack', (arg) {
      setState(() {
        historyList.add(
            "Resp：" + ResolveUtil.intList2String((arg as Uint8List).toList()));
      });
    });
  }
}
